﻿using System;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Sortable
{
    public class SortableItemContainerAdapter : ISortableItemContainer
    {
        private Object _source;
        private MethodInfo _sort;
        private PropertyInfo _expression;
        private PropertyInfo _direction;

        public SortableItemContainerAdapter(Object source, MethodInfo sort, PropertyInfo expression, PropertyInfo direction)
        {
            this._source = source;
            this._sort = sort;
            this._expression = expression;
            this._direction = direction;
        }

        public void Sort(string expression, SortDirection direction)
        {
            this._sort.Invoke(this._source, new object[] { expression, direction });
        }

        public string SortExpression
        {
            get { return (string)this._expression.GetValue(this._source, null); }
        }

        public SortDirection SortDirection
        {
            get { return (SortDirection)this._direction.GetValue(this._source, null); }
        }

        public static ISortableItemContainer GetAdapter(Control control)
        {
            ISortableItemContainer ret = null;

            var type = control.GetType();
            var type1 = typeof(string);
            var type2 = typeof(SortDirection);
            MethodInfo mi = type.GetMethod("Sort", new Type[] { type1, type2 });
            PropertyInfo pi1 = type.GetProperty("SortExpression", type1);
            PropertyInfo pi2 = type.GetProperty("SortDirection", type2);

            if (mi != null && pi1 != null && pi2 != null)
            {
                ret = new SortableItemContainerAdapter(control, mi, pi1, pi2);
            }

            return ret;
        }
    }
}